package com.xinsoft.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.ErpNoticeBillParam;
import com.xinsoft.entity.dto.ErpInOrOutStockParam;
import com.xinsoft.entity.dto.KisStockInOrOutDto;
import com.xinsoft.entity.dto.KisApiResultVOS;
import com.xinsoft.service.SyncPushBillService;
import com.xinsoft.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 	        rOB	trantype
 *
 * 委外入库   1       5
 * 委外出库   1       28
 * 委外退料  2       28
 *
 *
 * 采购入库   1       1
 * 采购退货   2       1
 *
 *
 * 生产入库   1       2
 * 生产退料   2       24   可能走倒冲
 * 生产领用   1      24
 *
 *
 * 销售出库   1       21
 * 销售退货	 2       21
 *
 *
 * 其他入库   1       10
 * 其他出库   1       29
 *
 * 调拨      1       41
 *
 * 盘盈      1       40
 * 盘亏      1       43
 */
@Slf4j
@Service
public class SyncPushBillKisImpl implements SyncPushBillService {


    @Resource
    private RedisUtil redisUtil;

    /**
     * 领料出库
     * @return
     */
    @Override
    public String feedingOutStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 24, params);
        log.info("MES->KIS领料出库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 生产退料入库
     *
     * @param params
     * @return
     */
    @Override
    public String feedingInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(2, 24, params);
        log.info("MES->KIS生产退料参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }


    /**
     * 生产入库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String produceInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 2, params);
        log.info("MES->KIS生产入库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 委外出库
     * @return
     */
    @Override
    public String sourcingFeedingOutStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 28, params);
        log.info("MES->KIS委外出库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 委外退料
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String sourcingReturnInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(2, 28, params);
        log.info("MES->KIS委外退料参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 委外入库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String sourcingFeedingInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 5, params);
        log.info("MES->KIS委外入库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 采购入库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String purchaseInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 1, params);
        log.info("MES->KIS采购入库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 采购退货
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String purchaseOutStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(2, 1, params);
        log.info("MES->KIS采购退货参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 其他入库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String otherInStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 10, params);
        log.info("MES->KIS其他入库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 其他出库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String otherOutStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 29, params);
        log.info("MES->KIS其他出库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 销售出库
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String saleOutStock(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 21, params);
        log.info("MES->KIS销售出库参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 库存调拨
     *
     * @param params
     * @return {@link String}
     */
    @Override
    public String inventoryTransfer(List<ErpInOrOutStockParam> params) {
        HashMap<String, Object> requestParam = getRequestParam(1, 41, params);
        log.info("MES->KIS库存调拨参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 盘盈
     *
     * @param profitList
     * @return {@link String}
     */
    @Override
    public String inventoryProfit(List<ErpInOrOutStockParam> profitList) {
        HashMap<String, Object> requestParam = getRequestParam(1, 40, profitList);
        log.info("MES->KIS盘盈参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    /**
     * 盘亏
     *
     * @param lossList
     * @return {@link String}
     */
    @Override
    public String inventoryLoss(List<ErpInOrOutStockParam> lossList) {
        HashMap<String, Object> requestParam = getRequestParam(1, 43, lossList);
        log.info("MES->KIS盘亏参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS.getMsg();
    }

    @Override
    public KisApiResultVOS purchaseNotice(List<ErpNoticeBillParam> params) {
        HashMap<String, Object> requestParam = getRequestParamOfNotice(1, 72, params);
        log.info("MES->KIS采购收料通知参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS;
    }

    @Override
    public KisApiResultVOS sourcingNotice(List<ErpNoticeBillParam> params) {
        HashMap<String, Object> requestParam = getRequestParamOfNotice(1, 72, params);
        log.info("MES->KIS委外收料通知参数：{}", JSON.toJSONString(requestParam));
        KisApiResultVOS kisApiResultVOS = postRequest(redisUtil.get(Const.ERP_CONNECT_URL).toString() + "/api/SaveBill", requestParam);
        return kisApiResultVOS;
    }

    /**
     * 封装出入库请求参数
     * @param rob
     * @param tranType
     * @param params
     * @return
     */
    public HashMap<String, Object> getRequestParam(Integer rob, Integer tranType, List<ErpInOrOutStockParam> params) {
        List<KisStockInOrOutDto> items = params.stream().map(ErpInOrOutStockParam::voToPo).collect(Collectors.toList());
        if (tranType.equals(21)) items.forEach(item -> item.setSrcTranTypeId("81"));
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Acct", "XRTEST");
        paramMap.put("rOB", rob);
        paramMap.put("trantype", tranType);
        paramMap.put("billEntrys", items);
        return paramMap;
    }

    /**
     * 封装收料通知请求参数
     * @param rob
     * @param tranType
     * @param params
     * @return
     */
    public HashMap<String, Object> getRequestParamOfNotice(Integer rob, Integer tranType, List<ErpNoticeBillParam> params) {
        List<KisStockInOrOutDto> items = params.stream().map(ErpNoticeBillParam::voToPo).collect(Collectors.toList());
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("Acct", "XRTEST");
        paramMap.put("rOB", rob);
        paramMap.put("trantype", tranType);
        paramMap.put("billEntrys", items);
        return paramMap;
    }

    public KisApiResultVOS postRequest(String url, HashMap<String, Object> paramMap) {
        String result = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json; charset=utf-8")// 头信息，多个头信息多次调用此方法即可
                .header(Header.ACCEPT, "application/json")// 头信息，多个头信息多次调用此方法即可
                // .form(paramMap)//表单内容
                .body(JSON.toJSONString(paramMap))
                .timeout(20000)// 超时，毫秒
                .execute().body();
        KisApiResultVOS apiResultVOS = JSON.parseObject(JSON.parseObject(result, String.class), KisApiResultVOS.class);
        log.info("---返回数据：" + JSON.toJSONString(result));
        // 0 为正常  1 异常
        if (ObjectUtil.isEmpty(apiResultVOS.getStatus()) || !apiResultVOS.getStatus().equals(0)) {
            throw new BDException("同步失败，请联系管理员！");
        }
        return apiResultVOS;
    }
}
